public class InitRegionRemainderActivityController
{
    //获得记录ID
   public String RecordId
   {
       get
       {
           if(System.currentPageReference().getParameters().get('id')!=NULL)
               return System.currentPageReference().getParameters().get('id').substring(0,15);  
           else
               return null;
       }
       set;
   }
    //获取Record Type Id
    public String RecordTypeId
    {
      
        get{        
                return System.currentPageReference().getParameters().get('RecordType');     
           }  
        set;
    }
   public CommonAttribute PlaceAttribute{get;set;}//公共属性
   public CommonMethod getComonMethod;//公共方法
    public Activity_Information__c ActivityInit{get;set;} //初始化活动对象
    public List<ActivityResourceEntry> ResourceEntryList{get;set;}//资源列表
    public List<ActivityCompetitionBrandEntry> CompetitionEntryList{get;set;}//竞品列表
    public List<ActivityParticipatorEntry> ParticipatorEntryList{get;set;}//参与者列表
    public List<SelectOption> CityOptionList{get;set;}//城市列表
    public Boolean IsSelectedAllCompetition{get;set;}//全选竞品信息
    public Boolean CheckParticipatorAll{get;set;}//选择所有的参与者
    public string SaveButtonText{get;set;}//保存按钮的文本显示
    public string CitySelectedValue{get;set;}//城市选择的值
    public Boolean IsNc{get;set;}//是否是NC店
    public Boolean IsDisplayForButtons{get;set;}//按钮是否可见
    public Boolean IsDisplayCancelActivity{get;set;}//取消按钮是否可见
    
    public set<string> ParticipatorKeyList;//参与列表键值.
    public set<string> AllParticipatorOutletList;//参与门店
    public set<string> AllcityList{get;set;}
    public User u{
     get{
       return getComonMethod.getUserInfo();
       }
    }   
    public set<String> areaList; 
    public InitRegionRemainderActivityController(ApexPages.StandardController controller)
    {
        IsDisplayForButtons=true;
        IsDisplayCancelActivity=true;
        
        getComonMethod=new CommonMethod();
        PlaceAttribute=new CommonAttribute();
        
        if(ResourceEntryList==NULL)
            ResourceEntryList=new List<ActivityResourceEntry>();
        else
            ResourceEntryList.clear();
            
         if(CompetitionEntryList==NULL)
             CompetitionEntryList=new List<ActivityCompetitionBrandEntry>();
         else
             CompetitionEntryList.clear();
             
         if(ParticipatorEntryList==NULL)
             ParticipatorEntryList=new List<ActivityParticipatorEntry>();
         else
             ParticipatorEntryList.clear();
             
         if(CityOptionList==NULL)
             CityOptionList=new List<SelectOption>();
        else
            CityOptionList.clear();
            
         if(AllcityList==NULL)
            AllcityList=new set<string>();
          else
              AllcityList.clear();
            
        if(ParticipatorKeyList==NULL)
            ParticipatorKeyList=new Set<string>();
        else
            ParticipatorKeyList.clear();
        if(AllParticipatorOutletLIst==NULL)
            AllParticipatorOutletList=new set<string>();
        else
            AllParticipatorOutletList.clear();
            
        areaList=new set<string>();
       
       CityOptionList.add(new SelectOption('0','ALL'));
                  
        if(RecordId==NULL)
        {
            SaveButtonText='保存并继续';
            ActivityInit=new Activity_Information__c();
           ActivityInit.RecordTypeId=RecordTypeId;
           ActivityInit.Activity_Stage__c='草稿';
           ActivityInit.Activity_Type_State__c='正常';
           
            //查找上个月盘点出的剩余ET数
            for(CheckInventory__c cInventory:GetCheckInventoryList())
            {
                 Resource_Allocation__c ra=new Resource_Allocation__c();
                 ra.CityName__c=cInventory.CityName__c;
                 ra.ETOrFGCode__c=cInventory.CityInventory__r.Product__r.SKU_Code__c;
                 ra.Product_Name__c=cInventory.CityInventory__r.Product__c;
                 ra.Resource_Type__c='ET';
                 ra.Resource_Allocation_Number__c=cInventory.ActualInventory__c;
                 ActivityResourceEntry entry=new ActivityResourceEntry(false,ra,0);
                 ResourceEntryList.add(entry);
                 
                 
                 if(!AllcityList.contains(ra.CityName__c))
                 {
                     CityOptionList.add(new SelectOption(ra.CityName__c,ra.CityName__c));
                     AllcityList.add(ra.CityName__c);
                 }
            }
        }
        else
        {
            SaveButtonText='保存';      
            ActivityInit=[Select Id,OwnerId,Name, RecordTypeId, ASMConfirmDate__c, ASMFinishDate__c, Activity_End_Date__c,
                                  Activity_Notice__c, Activity_Stage__c, Activity_Start_Date__c, Activity_Type_State__c, Activity_Type__c, 
                                  KAMConfirmDate__c, KAMFinishAdjustDate__c, NTMKTFinishApproveDate__c, RSMFinishApproveDate__c, 
                                  RTMFinishApproveDate__c, SRTMFinishApproveDate__c, SRTMFinishDate__c,Serial_Number__c,IsNcOrNotForRegion__c
                                  FROM Activity_Information__c where id=:RecordId];
                    
            //加载资源列
            set<string> resourceSetList=new set<string>();
            List<Resource_Allocation__c> resList=new List<Resource_Allocation__c>();
            for(Resource_Allocation__c res:[Select Activity_Information_Name__c,CityName__c,
                                                             Product_Code__c, Product_Name__c, Resource_Allocation_Number__c, Resource_Type__c,ETOrFGCode__c
                                                             FROM Resource_Allocation__c where Activity_Information_Name__c=:RecordId])
             {
                 resourceSetList.add(res.CityName__c+res.Product_Name__c);
                 resList.add(res);
             }
                                             
            if(ActivityInit.Activity_Stage__c=='草稿')
            {
                 //查找上个月盘点出的剩余ET数
                for(CheckInventory__c cInventory:GetCheckInventoryList())
                 {
                         Resource_Allocation__c ra=new Resource_Allocation__c();
                         ra.CityName__c=cInventory.CityName__c;
                         ra.ETOrFGCode__c=cInventory.CityInventory__r.Product__r.SKU_Code__c;
                         ra.Product_Name__c=cInventory.CityInventory__r.Product__c;
                         ra.Resource_Type__c='ET';
                         ra.Resource_Allocation_Number__c=cInventory.ActualInventory__c;
                          if(!resourceSetList.contains(cInventory.CityName__c+cInventory.CityInventory__r.Product__c))
                          {
                             ActivityResourceEntry entry=new ActivityResourceEntry(false,ra,0);
                             ResourceEntryList.add(entry);
                           }  
                          else
                          {
                              ActivityResourceEntry entry=new ActivityResourceEntry(true,ra,0);
                              ResourceEntryList.add(entry);
                          } 
                          
                          if(!AllcityList.contains(ra.CityName__c))
                         {
                             CityOptionList.add(new SelectOption(ra.CityName__c,ra.CityName__c));
                             AllcityList.add(ra.CityName__c);
                         }
                 }
            }
           else if(ActivityInit.OwnerId!=u.id || ActivityInit.Activity_Stage__c=='SRTM已发起活动' || ActivityInit.Activity_Stage__c=='活动已取消')
           {
                IsDisplayForButtons=false;
                for(Resource_Allocation__c res:resList)
                {
                     ActivityResourceEntry entry=new ActivityResourceEntry(false,res,0);
                     ResourceEntryList.add(entry);
                      if(!AllcityList.contains(res.CityName__c))
                      {
                           CityOptionList.add(new SelectOption(res.CityName__c,res.CityName__c));
                           AllcityList.add(res.CityName__c);
                      }
                 }
            }
            if(ActivityInit.OwnerId!=u.id)
                IsDisplayForButtons=false;
            //加载竞品
             for(Activity_Competition_Brand_Information__c acb:[Select  Name, Activity_Information__c, Type__c, Competition_Cost_Source__c, Competition_Cost_Type__c,
                                                 Competition_Promotion_Type__c FROM Activity_Competition_Brand_Information__c 
                                                 where Activity_Information__c=:RecordId])
            {
                CompetitionEntryList.add(new ActivityCompetitionBrandEntry(false,acb));
            }
            //加载参写者
            for(ParticipatorArea__c area: [Select Activity_Name__c, KA_Status__c, KA__c, OutletType__c, Channel__c, Outlet_Sum_Total__c,
                                                                                   Sub_region__c, Region__c,  Area__c,IsNCOrNot__c,City__c
                                                                                   FROM ParticipatorArea__c where Activity_Name__c=: RecordId])
            {
                String key=area.Region__c+area.City__c+area.OutletType__c+area.Channel__c+area.KA__c;
                ParticipatorKeyList.add(key);
                ParticipatorEntryList.add(new ActivityParticipatorEntry(false,area));    
            }
            
              //取消按钮是否显示
            Date StartDT=ActivityInit.Activity_Start_Date__c;                   
            if(Date.today()>= StartDT.addDays(-21))//开始活动前21天不可以调时间
                  IsDisplayCancelActivity=false;
            else
                 IsDisplayCancelActivity=true;
        }
    }
    public List<CheckInventory__c> GetCheckInventoryList()
    {
         //找出未开始和正在做的资源
            set<string> raList=new set<string>();
            for(Resource_Allocation__c ra:[select Product_Name__c from Resource_Allocation__c 
                                                                      where Product_Name__r.Product_Type__c='ET' 
                                                                      and (Activity_Information_Name__r.Activity_Start_Date__c>=TODAY
                                                                      or Activity_Information_Name__r.Activity_End_Date__c>=TODAY)
                                                                      and (Activity_Information_Name__r.Activity_Stage__c='总部已发起活动' 
                                                                      or Activity_Information_Name__r.Activity_Stage__c='SRTM已发起活动'
                                                                       or Activity_Information_Name__r.Activity_Stage__c='SRTM已发起活动')])
            {
                raList.add(ra.Product_Name__c);
            }
            
           List<CheckInventory__c> CheckList= [select CityName__c,ActualInventory__c,ProductName__c,
                                                                     CityInventory__r.Product__c,CityInventory__r.Product__r.SKU_Code__c
                                                                     from CheckInventory__c
                                                                     where 
                                                                     //CityInventory__r.Product__r.Product_Type__c='ET'
                                                                     CityInventory__r.ShipmentCity__r.Region__c=:getComonMethod.getUserRegion()
                                                                    // and CreatedDate=LAST_MONTH 
                                                                     and CityInventory__r.ShipmentCity__r.IsTrade__c=true
                                                                     and ActualInventory__c>0
                                                                     and CityInventory__r.Product__c not in: raList
                                                                     order by CreatedDate desc];
           map<string,CheckInventory__c>  mapCheckList=new map<string,CheckInventory__c>();                                        
           for(CheckInventory__c check:CheckList)
           {
               if(!mapCheckList.containsKey(check.CityName__c+check.CityInventory__r.Product__c))
               {
                   mapCheckList.put(check.CityName__c+check.CityInventory__r.Product__c,check);
               }
           }
           return mapCheckList.values();
    }
    //是否保存所有内容
    public void Save(boolean isSaveAll)
    {
        if(isSaveAll)
        {
            List<Resource_Allocation__c> raList=new List<Resource_Allocation__c>();
            map<string,List<Resource_Allocation__c>> cityResourceList=new map<string,List<Resource_Allocation__c>>();
             for(ActivityResourceEntry entry:ResourceEntryList)
            {
                if(entry.IsCheck)
                {
                   entry.Res.Activity_Information_Name__c=ActivityInit.id;
                   raList.add(entry.Res);
                   if(cityResourceList.containsKey(entry.Res.CityName__c))
                   {
                       List<Resource_Allocation__c> resourceList=cityResourceList.get(entry.Res.CityName__c);
                       resourceList.add(entry.Res);
                       cityResourceList.put(entry.Res.CityName__c,resourceList);
                   }
                   else
                   {
                       List<Resource_Allocation__c> resourceList=new List<Resource_Allocation__c>();
                       resourceList.add(entry.Res);
                       cityResourceList.put(entry.Res.CityName__c,resourceList);
                   }
                }
            }
            delete [select id from Resource_Allocation__c where Activity_Information_Name__c=:ActivityInit.id];
            insert raList;
            
            if(raList.size()==0)
                throw new CustomException('请选择参加活动的资源');
            if(ParticipatorEntryList.size()==0)
                throw new CustomException('请选择参与者');
            
            //查找参写者门店
            Map<string,List<Participator_Detail_Outlet__c>> ParticipatorOutletList=new Map<string,List<Participator_Detail_Outlet__c>>();
            Map<string,Integer> CityTargetNumberTotal=new Map<string,Integer>();//记录城市总的target
            List<Participator_Detail_Outlet__c> parDetailOutlet=[select id,City__c,Area__c,TargetNumber__c,Outlet_Name__c,OwnerId from Participator_Detail_Outlet__c where ActivityId__c=:RecordId];//总的参与者
            List<string> outletIdList=new List<string>();//记录所有的参与者的门店ID列表
            //查找参与者门店
            for(Participator_Detail_Outlet__c par:parDetailOutlet)
            {
                areaList.add(par.Area__c);
                outletIdList.add(par.Outlet_Name__c);
                if(ParticipatorOutletList.containsKey(par.City__c))
                {
                    List<Participator_Detail_Outlet__c> parList=ParticipatorOutletList.get(par.City__c);
                    parList.add(par);
                    ParticipatorOutletList.put(par.City__c,parList);
                }
                else
                {
                    List<Participator_Detail_Outlet__c> parList=new List<Participator_Detail_Outlet__c>();
                    parList.add(par);
                    ParticipatorOutletList.put(par.City__c,parList);
                }
           }
          
           //查找target值
             map<string,Integer> outletTargetList=new map<string,Integer>();
            for(Activity_Target_For_Outlet__c outlet:[select Target_Sum__c,Outlet__c from Activity_Target_For_Outlet__c where Outlet__c in: outletIdList])
                    outletTargetList.put(outlet.outlet__c,Integer.valueOf(outlet.Target_Sum__c));
                    
               //给门店target赋值
               for(Participator_Detail_Outlet__c pdo:parDetailOutlet)     
               {
                   if(outletTargetList.containsKey(pdo.Outlet_Name__c))
                       pdo.TargetNumber__c=Integer.valueOf(outletTargetList.get(pdo.Outlet_Name__c));
                       
                     //记录target
                    if(CityTargetNumberTotal.containsKey(pdo.City__c))
                    {
                        Integer Num=0;
                        if(CityTargetNumberTotal.get(pdo.City__c)!=NULL)
                            Num=CityTargetNumberTotal.get(pdo.City__c);
                            
                        if(pdo.TargetNumber__c>0)
                            Num+=Integer.valueOf(pdo.TargetNumber__c);
                            
                       CityTargetNumberTotal.put(pdo.City__c,Num);     
                    }
                    else
                    {
                        CityTargetNumberTotal.put(pdo.City__c,Integer.valueOf(pdo.TargetNumber__c));   
                    }
               }
               update parDetailOutlet;
          
            //分配资源
            //先删除
            delete [select id from Resource_Allocation_Detail__c where ActivityId__c=:RecordId];
            for(string key:cityResourceList.KeySet())
            {
                List<Resource_Allocation__c> resourceList=cityResourceList.get(key);//取出城市所对应的资源列表
                List<Participator_Detail_Outlet__c> parList=ParticipatorOutletList.get(key);//取出城市所对应的参与者列表
                Integer cityTotal=CityTargetNumberTotal.get(key);
                List<Resource_Allocation_Detail__c> radList=new List<Resource_Allocation_Detail__c>();
                Integer TotalAllocation=0;
                for(Resource_Allocation__c res:resourceList)
                {
                    radList.clear();
                    TotalAllocation=0;
                    for(Participator_Detail_Outlet__c par:parList)
                    {
                         Integer num=0;
                        if(par.TargetNumber__c!=NULL && cityTotal>0)
                            num=Integer.valueOf((par.TargetNumber__c/cityTotal)*res.Resource_Allocation_Number__c);
                            
                        Resource_Allocation_Detail__c rad=new Resource_Allocation_Detail__c();
                        rad.Participator_Detail_Outlet__c=par.id;
                        rad.Resource_Allocation__c=res.id;
                        rad.Resource_Quantity_Number__c=num;
                        radList.add(rad);
                        
                        TotalAllocation+=num;
                    }
                    getComonMethod.ReturnAdjustList(radList,TotalAllocation,res.Resource_Allocation_Number__c);
                }
            }
            
            //生成竞品信息
            List<Activity_Competition_Brand_Detail__c > acbdList=new List<Activity_Competition_Brand_Detail__c >();
            for(Activity_Competition_Brand_Information__c info:[select id from Activity_Competition_Brand_Information__c where Activity_Information__c=:RecordId])
            {
                for(Participator_Detail_Outlet__c pdo:parDetailOutlet)
                {
                    Activity_Competition_Brand_Detail__c acbd=new Activity_Competition_Brand_Detail__c(Activity_Competition_Brand_Information__c=info.id,
                                                                                                                                                         Participator_Detail_Outlet__c=pdo.Id,
                                                                                                                                                         OwnerId=pdo.OwnerId);
                    acbdList.add(acbd);
                }
            }
            delete [select id from Activity_Competition_Brand_Detail__c where ActivityId__c=:RecordId];
            insert acbdList;
        }
        else
        {
            insert ActivityInit;
        }
    }
     public PageReference addCompetitionBrandAction()
     {
         if(CompetitionEntryList==NULL)
             CompetitionEntryList=new  List<ActivityCompetitionBrandEntry>();
             try
             {
                 if(CompetitionEntryList.size()>=8)
                     throw new CustomException ('竞品类型不能超过8种');
                 if(PlaceAttribute.RegionPromotionTypeSelectedValue=='' || PlaceAttribute.RegionPromotionTypeSelectedValue==NULL)
                      throw new CustomException ('请选择竟品促销形式');
                 if(PlaceAttribute.RegionCostTypeSelectedValue=='' || PlaceAttribute.RegionCostTypeSelectedValue==NULL)
                      throw new CustomException ('请选择竞品费用形式');
                  if(PlaceAttribute.CostSourceSelectedValue=='' || PlaceAttribute.CostSourceSelectedValue==NULL)
                      throw new CustomException ('请选择竞品费用来源');
                      
                   for(ActivityCompetitionBrandEntry entry:CompetitionEntryList)   
                   {
                       if(entry.ActivityCompetitionMsg.Competition_Cost_Source__c==PlaceAttribute.CostSourceSelectedValue &&
                          entry.ActivityCompetitionMsg.Competition_Cost_Type__c== PlaceAttribute.RegionCostTypeSelectedValue&&
                          entry.ActivityCompetitionMsg.Competition_Promotion_Type__c==PlaceAttribute.RegionPromotionTypeSelectedValue)
                              return null;
                   }
                    Activity_Competition_Brand_Information__c activity=new Activity_Competition_Brand_Information__c(Activity_Information__c=ActivityInit.id,
                                                                                                  Competition_Cost_Source__c=PlaceAttribute.CostSourceSelectedValue,
                                                                                                  Competition_Cost_Type__c=PlaceAttribute.RegionCostTypeSelectedValue,
                                                                                                   Competition_Promotion_Type__c=PlaceAttribute.RegionPromotionTypeSelectedValue,
                                                                                                    Type__c='ET');
                   CompetitionEntryList.add(new ActivityCompetitionBrandEntry(false,activity));
                   insert activity;
             }
             catch(Exception ex)
             {
                  ApexPages.addMessages(ex);
                 return null;
             }
             PlaceAttribute.RegionPromotionTypeSelectedValue='';
             PlaceAttribute.RegionCostTypeSelectedValue='';
             PlaceAttribute.CostSourceSelectedValue='';
             
             return null;
     }
     //删除竞品信息
      public PageReference DeleteCompetitionBrandAction()
      {
         for(Integer i=0;i<CompetitionEntryList.size();i++)
         {
              ActivityCompetitionBrandEntry entry=CompetitionEntryList[i];
             if(entry.IsCheck)
             {
                 CompetitionEntryList.remove(i);
                 delete [select id from Activity_Competition_Brand_Information__c where id=:entry.ActivityCompetitionMsg.Id];
                 i--;
             }
         }
          return null;
      }
    public PageReference AddParticipator()
    {
        List<Participator_Detail_Outlet__c> outletDetail=new List<Participator_Detail_Outlet__c>();
         for(Participator_Detail_Outlet__c par:[select Outlet_Name__c from Participator_Detail_Outlet__c where Participator_Area__r.Activity_Name__c=:RecordId])
         {
               AllParticipatorOutletList.add(par.Outlet_Name__c);
          }
          string sql='';
           if(CitySelectedValue==NULL || CitySelectedValue=='0')//选择所有的门店
           {
               string filterStr='';
               for(string str:AllcityList)
                {
                    if(filterStr!='')
                        filterStr+=' or ';
                   filterStr+=' CityName__c=\''+str+'\'';
                }   
                 sql='select id,OwnerId from Account where Active_Status__c=\'正常营业\' and  OutletRegion__c=\''+getComonMethod.getUserRegion()+'\''+Filter();
                 if(filterStr!='')
                     sql+=' and ('+filterStr+')';
           }
           else
                sql='select id,OwnerId from Account where Active_Status__c=\'正常营业\' and  CityName__c=\''+CitySelectedValue+'\''+Filter();
                
                  List<Account> ListCountLastActual=new  List<Account>();
                  ListCountLastActual=Database.Query(sql);  
             
                 String key=getComonMethod.getUserRegion()+CitySelectedValue+PlaceAttribute.OutletTypeSelectedValue+PlaceAttribute.ChannelSelectedValue+PlaceAttribute.KASelectedValue;
                   if(!ParticipatorKeyList.contains(key))
                   {
                        ParticipatorArea__c par=null;
                        if(CitySelectedValue==NULL || CitySelectedValue=='0')
                        {
                             par=new ParticipatorArea__c(Activity_Name__c=RecordId,
                                                                          Region__c=getComonMethod.getUserRegion(),
                                                                          OutletType__c=PlaceAttribute.OutletTypeSelectedValue,
                                                                          Channel__c=PlaceAttribute.ChannelSelectedValue,
                                                                          KA__c=PlaceAttribute.KASelectedValue,
                                                                          IsNCOrNot__c=ActivityInit.IsNcOrNotForRegion__c,
                                                                          Outlet_Sum_Total__c=ListCountLastActual.size());
                        }
                        else
                         {
                            par=new ParticipatorArea__c(Activity_Name__c=RecordId,
                                                                          Region__c=getComonMethod.getUserRegion(),
                                                                          City__c=CitySelectedValue,
                                                                          OutletType__c=PlaceAttribute.OutletTypeSelectedValue,
                                                                          Channel__c=PlaceAttribute.ChannelSelectedValue,
                                                                          KA__c=PlaceAttribute.KASelectedValue,
                                                                          IsNCOrNot__c=ActivityInit.IsNcOrNotForRegion__c,
                                                                          Outlet_Sum_Total__c=ListCountLastActual.size());
                          }     
                                                                             
                           insert par;  
                          ParticipatorKeyList.add(key);
                          
                           for(Account acc:ListCountLastActual)
                            {
                               if(!AllParticipatorOutletList.contains(acc.Id))
                                {
                                    outletDetail.add(new Participator_Detail_Outlet__c(Outlet_Name__c=acc.id,
                                                                                                                    Participator_Area__c=par.Id,
                                                                                                                   Outlet_Type__c='正常营业',
                                                                                                                   OwnerId=acc.OwnerId));
                                    AllParticipatorOutletList.add(acc.id);                                                                                        
                                }
                            }
                          insert  outletDetail;
                          if(outletDetail.size()!=ListCountLastActual.size())
                          {
                              par.Outlet_Sum_Total__c=outletDetail.size();
                              update par;
                          }
                        ParticipatorEntryList.add(new ActivityParticipatorEntry (false,par));
                    }
                     return null;
        }
    
     //删除参与者
     public PageReference DelParticipator()
     {
         for(Integer i=0;i<ParticipatorEntryList.size();i++)
         {
             ActivityParticipatorEntry entry=ParticipatorEntryList[i];
             if(entry.IsCheck)
             {
                 String key=getComonMethod.getUserRegion()+CitySelectedValue+PlaceAttribute.OutletTypeSelectedValue+PlaceAttribute.ChannelSelectedValue+PlaceAttribute.KASelectedValue;    
                 ParticipatorKeyList.remove(key);   
                  
                 ParticipatorEntryList.remove(i);
                 delete [select id from Participator_Detail_Outlet__c where Participator_Area__c=:entry.ParArea.Id];
                 delete [select id from ParticipatorArea__c where Id=:entry.ParArea.Id];
                 i--;
             }
         }
         return null;
     }
     
     public PageReference SaveData()
     {
       //  try
      //   {
             if(SaveButtonText=='保存')
             {
                 Save(true);
                 update ActivityInit;
                 PageReference pr=new PageReference('/'+ActivityInit.id);
                 pr.setRedirect(true);
                 return pr;
              }
             else
             {
                 Save(false);
                 PageReference pr=new PageReference('/apex/InitRegionRemainderActivity?id='+ActivityInit.id);
                 pr.setRedirect(true);
                 return pr;
              }
    //   }
      //   catch(Exception ex)
      //   {
      //       ApexPages.addMessages(ex);
      //        return null;
     //    }
         return null;
     }
     public PageReference  Submit()
     {
       //  try
       //  {
             ActivityInit.Activity_Stage__c='SRTM已发起活动';
             update ActivityInit;
             Save(true);
      //   }
    //     catch(Exception ex)
     //    {
      //        ApexPages.addMessages(ex);
      //        return null;
      //   }
       //发邮件给ASM
         String BodyString='请登陆凤凰系统，调整并且确认【'+ActivityInit.Name+'】活动的资源';
         String rg=getComonMethod.getUserRegion();
         List<String> ToAddress=getToAddress(RecordId);
         String subject='活动调整，活动名称:'+ActivityInit.Name;
          //System.assert(false,ToAddress);
          EmailHander.SendMail(BodyString,ToAddress,subject,'',null);
         PageReference pr=new PageReference('/'+ActivityInit.id);
         pr.setRedirect(true);
         return pr;
     }
       //取消活动
        public PageReference CancelActivity()
        {
             if(RecordId!=NULL)
             {
                     ActivityInit.Activity_Stage__c='活动已取消';
                     ActivityInit.Activity_Type_State__c='取消';
                     update ActivityInit;
             }
            pageReference pr = new pageReference('/'+ActivityInit.id);     
            pr.setredirect(true);   
            return pr;
        }
        
          //条件过滤
      public String Filter()
      {
            String filter='';
          if(PlaceAttribute.OutletTypeSelectedValue!='' && PlaceAttribute.OutletTypeSelectedValue!=NULL)
          {
                    filter+=' and ';
                    filter+='Outlet_Type__c=\''+PlaceAttribute.OutletTypeSelectedValue+'\'';
           }
           if(PlaceAttribute.ChannelSelectedValue!='' && PlaceAttribute.ChannelSelectedValue!=NULL)
           {
                  filter+=' and ';
                 filter+='Channel__c=\''+PlaceAttribute.ChannelSelectedValue+'\'';
           }
           if(PlaceAttribute.KASelectedValue!='' && PlaceAttribute.KASelectedValue!=NULL)
           {
               filter+=' and ';
               filter+='Chain_Customer__c=\''+PlaceAttribute.KASelectedValue+'\'';
           }
          if(ActivityInit.IsNcOrNotForRegion__c==true)//是否是NC店
              filter+=' and With_NC_or_not__c ='+ActivityInit.IsNcOrNotForRegion__c;
              
              return filter;
      }        
      
       //获取 ASM邮件地址 ,用于NTMKT发送邮件给ASM
       public List<String> getToAddress(String RecordId){
           set<string> rsmIdList=new set<string>();
           List<string> ToAddress=new List<string>();
            //找出所有直接汇报给RSM ID
            for(User u:[select id from User where Title__c='Regional Sales Manager' and UserSubRegion__c in:areaList])
                rsmIdList.add(u.id);
                
          //找出所有的ASM ID 
          for(User u:[select id,Email from User where Title__c='Area/District Sales Manager' and UserAreaValue__c in:areaList and ManagerId in:rsmIdList])
             ToAddress.add(u.Email);
              
             return ToAddress;  
    }     
    
     public PageReference ParticipatorOnCheckAction()
      {
            try
            {
                 if(ActivityInit.Activity_Stage__c=='草稿 ')
                 {   
                        delete [select id from Participator_Detail_Outlet__c where Participator_Area__r.Activity_Name__c=:ActivityInit.id ];
                        delete [select id from ParticipatorArea__c where Activity_Name__c=:ActivityInit.id];
                        ParticipatorKeyList.clear();
                        ParticipatorEntryList.clear();
                  }
            }
            catch(DMLException ex)
            {
                ApexPages.addMessages(new CustomException('由于数据量大，请分多次删除数据'));
                 return null;
            }
            return null;
      }
}